package com.eeGroup.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Autowired
    private UserRealm userRealm;

    // 安全管理器
    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    // Shiro 过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        // 自定义过滤器
        Map<String, javax.servlet.Filter> filters = new LinkedHashMap<>();
        filters.put("authc", new CustomFormAuthenticationFilter()); // 替换默认的 FormAuthenticationFilter
        shiroFilter.setFilters(filters);

        // 设置登录页
        shiroFilter.setLoginUrl("/login");
        // 设置未授权页面
        shiroFilter.setUnauthorizedUrl("/unauthorize");

        // 配置拦截规则
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 登录
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/doLogin", "anon");

        // 静态资源无需认证
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/scripts/**", "anon");
        filterChainDefinitionMap.put("/common/**", "anon");

        filterChainDefinitionMap.put("/*.html", "anon");
        filterChainDefinitionMap.put("/favicon.ico", "anon");


        filterChainDefinitionMap.put("/**", "authc"); // 其他路径需要认证
        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilter;
    }
}
